from django.apps import apps
from django.contrib import admin

# Register your models here.
from django.contrib.admin import helpers
from django.contrib.auth.models import User
from django.utils.html import format_html

from nav.filter import Role_nav_Filter, Nar_bar_Filter
from nav.models import Role_nav, Nav_bar, Left_bar, Links, Solink


class Role_navAdmin(admin.ModelAdmin):
    list_display = ('id','title',"createUser","buttons")
    #list_filter = ('title',"createUser")
    ##raw_id_fields=('salemanTeam')
    list_display_links = ( 'id',"title",)
    search_fields = ['title']
    list_editable =[]
    ordering = ('title',)

    def buttons(self, obj):
        button_html = """<a class="changelink" target="_blank" href="/nav/%s">预览</a>""" %(obj.id)
        return format_html(button_html)

    buttons.short_description = "操作"

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(createUser=request.user)


    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == 'createUser':
            kwargs['queryset'] = User.objects.filter(username=request.user.username)
        return super(Role_navAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

    def get_readonly_fields(self, request, obj=None):
        if obj is not None:
            return self.readonly_fields + ('createUser',)
        return self.readonly_fields

    def add_view(self, request, form_url="", extra_context=None):
        data = request.GET.copy()
        data['createUser'] = request.user
        request.GET = data
        return super(Role_navAdmin, self).add_view(request, form_url="", extra_context=extra_context)


class Nav_barAdmin(admin.ModelAdmin):
    list_display = ('id','role_nav','title',"icon")
    list_filter = [Role_nav_Filter]
    ##raw_id_fields=('salemanTeam')
    list_display_links = ( 'title',)
    search_fields = ('title',)
    #list_editable =[]
    ordering = ('title',)


    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs

        role_navs = Role_nav.objects.filter(createUser = request.user).all()
        return qs.filter(role_nav__in=role_navs)

    def add_view(self, request, form_url="", extra_context=None):
        ModelForm = self.get_form(request)
        if request.POST:
            form = ModelForm(request.POST, request.FILES)
        else:
            form = ModelForm()

        qs = form['role_nav'].field.queryset
        qs = qs.filter(createUser=request.user)
        form['role_nav'].field.queryset = qs
        adminForm = helpers.AdminForm(form, list(self.get_fieldsets(request)),
                                      self.prepopulated_fields, self.get_readonly_fields(request),
                                      model_admin=self)
        context = {
            'form': form,
            'adminform': adminForm,
            'show_delete': False
        }
        context.update(extra_context or {})

        return super(Nav_barAdmin, self).add_view(request, form_url="", extra_context=context)


class Left_barAdmin(admin.ModelAdmin):
    list_display = ('id','nav_bar','title',"icon")
    list_display_links = ('title',)
    list_filter = [Nar_bar_Filter]
    search_fields = ['title']


    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs

        role_navs = Role_nav.objects.filter(createUser = request.user).all()
        nav_bars = Nav_bar.objects.filter(role_nav__in=role_navs)
        return qs.filter(nav_bar__in=nav_bars)


    def add_view(self, request, form_url="", extra_context=None):
        ModelForm = self.get_form(request)
        if request.POST:
            form = ModelForm(request.POST, request.FILES)
        else:
            form = ModelForm()

        qs = form['nav_bar'].field.queryset

        role_navs = Role_nav.objects.filter(createUser=request.user).all()
        qs = qs.filter(role_nav__in=role_navs)
        form['nav_bar'].field.queryset = qs
        adminForm = helpers.AdminForm(form, list(self.get_fieldsets(request)),
                                      self.prepopulated_fields, self.get_readonly_fields(request),
                                      model_admin=self)
        context = {
            'form':form,
            'adminform': adminForm,
            'show_delete': False
        }
        context.update(extra_context or {})

        #return self.render_change_form(request, context, form_url=form_url, add=True)
        return super(Left_barAdmin, self).add_view(request, form_url="", extra_context=context)




class LinksAdmin(admin.ModelAdmin):
    list_display = ('id','show_nav_bar_title','left_bar','title',"icon","url")
    list_display_links = ('title',)
    list_filter = ['left_bar']
    search_fields = ['title']

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs

        role_navs = Role_nav.objects.filter(createUser = request.user).all()
        nar_bars=Nav_bar.objects.filter(role_nav__in=role_navs)
        left_bars=Left_bar.objects.filter(nav_bar__in=nar_bars)
        return qs.filter(left_bar__in=left_bars)

    def add_view(self, request, form_url="", extra_context=None):
        ModelForm = self.get_form(request)
        if request.POST:
            form = ModelForm(request.POST, request.FILES)
        else:
            form = ModelForm()

        qs = form['left_bar'].field.queryset

        role_navs = Role_nav.objects.filter(createUser=request.user).all()
        nav_bars=Nav_bar.objects.filter(role_nav__in=role_navs).all()

        qs = qs.filter(nav_bar__in=nav_bars)
        form['left_bar'].field.queryset = qs
        adminForm = helpers.AdminForm(form, list(self.get_fieldsets(request)),
                                      self.prepopulated_fields, self.get_readonly_fields(request),
                                      model_admin=self)
        context = {
            'form':form,
            'adminform': adminForm,
            'show_delete': False
        }
        context.update(extra_context or {})

        #return self.render_change_form(request, context, form_url=form_url, add=True)
        return super(LinksAdmin, self).add_view(request, form_url="", extra_context=context)



class SolinksAdmin(admin.ModelAdmin):
    list_display = ('id','role_nav','title',"icon","url")
    list_display_links = ('title',)
    list_filter = [Role_nav_Filter]
    search_fields = ['title']

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs

        role_navs = Role_nav.objects.filter(createUser = request.user).all()
        return qs.filter(role_nav__in=role_navs)


    def add_view(self, request, form_url="", extra_context=None):
        ModelForm = self.get_form(request)
        if request.POST:
            form = ModelForm(request.POST, request.FILES)
        else:
            form = ModelForm()

        qs = form['role_nav'].field.queryset
        qs = qs.filter(createUser=request.user)
        form['role_nav'].field.queryset = qs
        adminForm = helpers.AdminForm(form, list(self.get_fieldsets(request)),
                                      self.prepopulated_fields, self.get_readonly_fields(request),
                                      model_admin=self)
        context = {
            'form':form,
            'adminform': adminForm,
            'show_delete': False
        }
        context.update(extra_context or {})


        return super(SolinksAdmin, self).add_view(request, form_url="", extra_context=context)



admin.site.register(Role_nav, Role_navAdmin)
admin.site.register(Left_bar, Left_barAdmin)
admin.site.register(Nav_bar, Nav_barAdmin)
admin.site.register(Links, LinksAdmin)
admin.site.register(Solink, SolinksAdmin)

# 指定导航顺序
apps_index = ["Role_nav", "Solink","Nav_bar", "Left_bar", "Links"]

def find_app_index(app_label):
    app = apps.get_app_config(app_label)
    main_menu_index = getattr(app, 'main_menu_index', 9999)
    return main_menu_index


def index_decorator(func):
    def inner(*args, **kwargs):
        templateresponse = func(*args, **kwargs)
        app_list = templateresponse.context_data['app_list']
        app_list.sort(key=lambda r: find_app_index(r['app_label']))
        #print("app_list:", app_list)
        for app in app_list:
            if app["app_label"] == "nav":
                # 按照指定顺序排序
                models = app["models"]
                new_models = []
                for i in models:
                    model_name = i["object_name"]
                    pos = apps_index.index(model_name)
                    new_models.append({"pos": pos, "model": i})
                new_models.sort(key=lambda s: s["pos"])
                #app['models'].sort(key=lambda x: find_model_index(x['name']))
                models = [x["model"] for x in new_models]
                app["models"] = models
                #print("models:", models)

        return templateresponse

    return inner


admin.site.index = index_decorator(admin.site.index)
admin.site.app_index = index_decorator(admin.site.app_index)
title="导航网址生成系统"
admin.site.site_header = title
admin.site.site_title = title
admin.site.index_title = title

